<template>
<div class="pane">
    <div v-if="!friendModel">
        <el-input v-model="username" placeholder="请输入用户账号" clearable>
            <template #append>
                <el-button :icon="Search" @click="searchAccountUser"/>
            </template>
        </el-input>
    </div>
    <div v-show="showUserInfo"  :class="{ showTip: isActive,'user_info':true}">
        <el-form :model="inputReq" :rules="rules" ref="formRef" label="0px">
            <el-descriptions 
                :column="2"
                 title="用户详情" border>
                <el-descriptions-item
                :rowspan="2"
                :width="100"
                label="Photo"
                >
                <el-image
                    style="width: 100px; height: 100px"
                    src="/img/user.png"
                />
                </el-descriptions-item>
                <el-descriptions-item label="账号" >
                    <div class="info_item">
                        {{ userInfo.username }}
                    </div>
                    
                </el-descriptions-item>
                <el-descriptions-item label="手机号" >{{ userInfo.phone }}</el-descriptions-item>
                <el-descriptions-item label="用户id"   :span="2">
                    {{ userInfo.uuid }}
                </el-descriptions-item>
                <el-descriptions-item label="转账金额" :span="2">
                    <el-form-item prop="payMoney">
                        <el-input v-model="inputReq.payMoney" placeholder="请输入转账金额" clearable></el-input>
                    </el-form-item>
                </el-descriptions-item>
                <el-descriptions-item label="转账备注" :span="2">
                    <el-form-item prop="payNote">
                         <el-input v-model="inputReq.payNote" placeholder="请输入转账备注" clearable></el-input>
                    </el-form-item>
                </el-descriptions-item>
                <el-descriptions-item label="支付密码" :span="2">
                    <el-form-item prop="payPassword">
                         <el-input v-model="inputReq.payPassword" type="password" placeholder="请输入转账密码" clearable></el-input>
                    </el-form-item>
                </el-descriptions-item>              
            </el-descriptions>
        </el-form>
    </div>
</div>
</template>
<script setup>
import { defineComponent,reactive, ref, unref, h, onMounted, nextTick, computed, getCurrentInstance,watch,toRefs} from 'vue'
import { Search } from '@element-plus/icons-vue';
import { userApi } from '@/api/apis/user';

// 定义事件让子组件调用父组件
const emit = defineEmits(['transferRequest']);
//是否是好友模式
const friendModel=ref(false);

const formRef = ref(null);
const username=ref('');
const showUserInfo=ref(false);
const isActive=ref(true);
const userInfo=reactive({
    uuid:'',
    username:'',
    phone:'',
    userId:'',
    idCard:''
})
//设置朋友模式
const setFriendModel=(userId)=>{
    friendModel.value=true;
    searchAccountUserUserId(userId);
}

// 自定义验证规则
const validateAmount = (rule, value, callback) => {
  if (!value) {
    return callback(new Error('金额不能为空'))
  }
  
  // 金额格式：支持正数、小数（最多2位小数）
  const amountRegex = /^(?:0|[1-9]\d*)(?:\.\d{1,2})?$/
  if (!amountRegex.test(value)) {
    return callback(new Error('请输入正确的金额格式（最多2位小数）'))
  }
  
  // 金额范围验证（可选）
  const numValue = parseFloat(value)
  if (numValue < 0) {
    return callback(new Error('金额不能为负数'))
  }
  
  if (numValue > 1000000) {
    return callback(new Error('金额不能超过100万'))
  }
  
  callback()
}
// 验证规则
const rules = reactive({
  payMoney:[
    { validator: validateAmount, trigger: 'blur' }
  ], 
  payNote:[
    { required: true, message: '请输入转账备注', trigger: 'blur' },
    { min: 1, max: 10, message: '长度在 1 到 10 个字符', trigger: 'blur' }
  ],
   payPassword:[
    { required: true, message: '请输入支付密码', trigger: 'blur' },
    { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
  ],
  userName: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
  ],
  mail: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
  ]
})
const inputReq=reactive({
    payMoney:0,
    payNote:'汇款',
    payPassword:'',
    userName:'',
})
// 监听多个 ref 或 reactive 属性
watch([
    () => inputReq.payMoney,
    () => inputReq.payPassword
  ],
  ([newPayMoney, newPayPassword], [payMoney, payPassword]) => {
    formRef.value.validate()
    .then(() => {
        isActive.value=true;
        let reqData=unref(inputReq);
        console.log(JSON.stringify(reqData));
        emit('transferRequest',{code:true,data:reqData});
    }).catch((error) => {
        isActive.value=false;
         emit('transferRequest',{code:false});
    })
  }
)
//搜索用户通过用户id
const searchAccountUserUserId=(userId)=>{
    userApi.searchUserByUid(userId).then((res)=>{
        if(res){
            Object.assign(userInfo, res);
            inputReq.userName=res.username;
            showUserInfo.value=true;
        }else{
            showUserInfo.value=false;
             emit('transferRequest',{code:false});
        }
    }).catch((err)=>{
        showUserInfo.value=false;
         emit('transferRequest',{code:false});
    })
}
//搜索用户
const searchAccountUser=()=>{
    userApi.searchUser(username.value).then((res)=>{
        if(res){
            Object.assign(userInfo, res);
            inputReq.userName=res.username;
            showUserInfo.value=true;
        }else{
            showUserInfo.value=false;
             emit('transferRequest',{code:false});
        }
    }).catch((err)=>{
        showUserInfo.value=false;
         emit('transferRequest',{code:false});
    })
}
// 暴露方法给父组件
defineExpose({
    setFriendModel
})
</script>
<style lang="css" scoped>
.pane{
    .user_info{
        margin-top: 8px;
        box-sizing: border-box;
        padding: 20px;
        border: 1px solid #dcdfe6;
        border-radius: 4px;
    }
    .showTip{
        .el-form-item{
             margin-bottom: 0px;
        }
    }
   
}
.info_item{
    width: 200px;
}
</style>